<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

function checkAuthentication($postVars=NULL,$serverVars=NULL) {
	$CI =& get_instance();
    $CI->load->model('users/User_login','',TRUE);
    $CI->load->model('users/User_information','',TRUE);
    $CI->load->model('contacts/Contacts','',TRUE);
    $CI->load->model('accounts/Accounts','',TRUE);
    $CI->load->library('encrypt');
    $CI->load->helper('zend');

	/*
	 * First let's check for authentication from the
	 * desktop client.
	 */    
	$authKey = '';
	if (isset($postVars['authKey'])) {
		$authKey = $postVars['authKey'];
		/*
		 * Check authKey against database to see if we have a valid
		 * authenticated user.
		 */
        $CI->encrypt->set_cipher(MCRYPT_BLOWFISH);
        $decryptAuthKey = $CI->encrypt->decode($postVars['authKey']);
        $auth = $CI->User_login->checkAuthKey($decryptAuthKey);
		if ($auth == false) {
			exit('{"Error":"1","ErrorMessage":"AuthKeyError"}');
		} else {
            $userid = $auth['UID'];
            $accountUserid = $auth['UseridAccount'];
            $accountInfo = $CI->Accounts->getAccountInformation($accountUserid);
            $userInformationArray = $CI->Contacts->getContactPerson(null,$userid);

            $CI->session->set_userdata('accountUserid',$accountUserid);
            $CI->session->set_userdata('currency',$accountInfo['Currency']);
            $CI->session->set_userdata('userid',$userid);
            $CI->session->set_userdata('RoleName',$auth['RoleName']);
            $CI->session->set_userdata('pid',$userInformationArray['PID']);
            $CI->session->set_userdata('permissions',createPermissionsArray($auth['RolePermissions']));
        }
	} elseif($CI->session->userdata('logged') != TRUE) {
        /*
         * Is this an AJAX request?
         */
        if (isset($serverVars['HTTP_X_REQUESTED_WITH']) && $serverVars['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
            header("HTTP/1.0 403 Forbidden");
            exit;
        } else {
            header("Status: 200");
            header('Location: '.site_url('login'));
            exit;
        }
	} else {
        /*
         * If we're logged into the web app, see if we need to
         * be sent to the pay-me-now page.
         */
        $daysFromSignup = days_between_dates(strtotime($CI->session->userdata('dateSignup')),time());
        if ($CI->session->userdata('accountLevel') > 0 && $CI->session->userdata('isPaid') == FALSE && $CI->session->userdata('userType') != USER_TYPE_CLIENT) {
            if ($daysFromSignup >= 31) {
                header('Location: '.SECURE_URL.'payment/paymentInfo/'.$CI->session->userdata('accountUserid'));
            }
        }

        /*
         * Finally, let's see if the application is offline.
         */
        if (IS_OFFLINE == TRUE) {
            header('Location: '.INSECURE_URL.'error/offline');
        }
    }
    if (!empty($serverVars['QUERY_STRING'])) {
        /*
         * Let's assume we'll only have 1 query parameter
         */
        $qArray = explode('=',$serverVars['QUERY_STRING']);
        $googleToken = $CI->session->userdata('googleToken');
        if ($qArray[0] == 'token' && empty($googleToken)) {
            /*
             * This is a Google docs auth request
             */
            Zend_Loader::loadClass('Zend_Gdata_AuthSub');
            $googleToken = urldecode($qArray[1]);
            $CI->session->set_userdata('googleToken',Zend_Gdata_AuthSub::getAuthSubSessionToken($googleToken));
        }
    }
}

function checkAuthKeyFromGetRequest($uriString,$fromWhat=NULL,$api=FALSE) {
    /*
     * Parse the uriString on / and look for the authKey.
     * Check auth key against user database. If there's a match
     * and the user is God, then return true.
     * If there's a match and user is client, the login as client.
     * Otherwise, return false.
     * URI will be in the form of /index.php/<directory>/<controller>/<method>/<authString>
     */
    $CI =& get_instance();
    $CI->load->model('users/User_login','',TRUE);
    $CI->load->model('settings/settings_update','Settings',TRUE);
    $CI->load->library('application/CommonLogin');

    $uriArray = explode('/',$uriString);
    $authKey = $uriArray[5];
    if (!empty($authKey)) {
        /*
         * Check for valid authKey
         */
        $loginArrayAccount  = $CI->User_login->checkAuthString($authKey,'account');
        $loginArrayPersonal = $CI->User_login->checkAuthString($authKey,'personal');
        $loginArrayClient   = $CI->User_login->checkAuthString($authKey,'client');
        $loginSetting = array();

        if ($loginArrayAccount != FALSE) {
            //return $loginArrayAccount['AccountID'];
            $loginArrayAccount['UseridAccount'] = $loginArrayAccount['AccountID'];
            $loginArrayAccount['Language'] = '';
            return $loginArrayAccount;
        } elseif ($loginArrayPersonal != FALSE) {
            if ($CI->session->userdata('logged') != TRUE) {
                /*
                 * Get setting for auto login from GET request
                 */
                if ($fromWhat == 'email') {
                    $loginSetting = $CI->Settings->getSettings($loginArrayPersonal['UseridAccount'],'accountLoginFromEmail');
                } elseif($fromWhat == 'item') {
                    $loginSetting = $CI->Settings->getSettings($loginArrayPersonal['UseridAccount'],'accountLoginFromItemView');
                }
                if (isset($loginSetting['SettingValue']) && $loginSetting['SettingValue'] == 1) {
                    $CI->commonlogin->doLogin($loginArrayPersonal,FALSE);
                }
            }
            return $loginArrayPersonal;
        } elseif ($loginArrayClient != FALSE) {
            if ($CI->session->userdata('logged') != TRUE) {
                /*
                 * Get setting for auto login from GET request
                 */
                if ($fromWhat == 'email') {
                    $loginSetting = $CI->Settings->getSettings($loginArrayClient['UID'],'accountLoginFromEmail','client');
                } elseif($fromWhat == 'item') {
                    $loginSetting = $CI->Settings->getSettings($loginArrayClient['UID'],'accountLoginFromItemView','client');
                }
                if (isset($loginSetting['SettingValue']) && $loginSetting['SettingValue'] == 1) {
                    $CI->commonlogin->doLogin($loginArrayClient,FALSE);
                }
            }
            return $loginArrayClient;
        } else {
            $error = 1;
        }
    } else {
        $error = 1;
    }

    if ($error == 1) {
		if ($api == TRUE || $api == 1) {
			echo '{"Error":"1","ErrorMessage":"'.$error.'"}';
		} else {
			header('Location: '.site_url('login'));
			exit;
		}
    }
}

function createPermissionsArray($permString) {
    if (empty($permString)) {
        return FALSE;
    }

    $permChunkArray = explode('-',$permString);
    $client    = $permChunkArray[0];
    $project   = $permChunkArray[1];
    $task      = $permChunkArray[2];
    $invoice   = $permChunkArray[3];
    $expense   = $permChunkArray[4];
    $timesheet = $permChunkArray[5];
    $file      = $permChunkArray[6];
    $team      = $permChunkArray[7];
    $message   = $permChunkArray[8];
    $calendar  = $permChunkArray[9];
    $contact   = $permChunkArray[10];
    $trash     = $permChunkArray[11];
    $settings  = $permChunkArray[12];

    $permissions = array(
        'clientView'   => $client{0},
        'clientCreate' => $client{1},
        'clientUpdate' => $client{2},
        'clientDelete' => $client{3},

        'projectViewAll' => $project{0},
        'projectViewOwn' => $project{1},
        'projectCreate'  => $project{2},
        'projectUpdate'  => $project{3},
        'projectDelete'  => $project{4},

        'taskViewAll' => $task{0},
        'taskViewOwn' => $task{1},
        'taskCreate'  => $task{2},
        'taskUpdate'  => $task{3},
        'taskDelete'  => $task{4},

        'invoiceViewAll'    => $invoice{0},
        'invoiceViewOwn'    => $invoice{1},
        'invoiceCreateSend' => $invoice{2},
        'invoiceCreateSendToAccountOwner' => $invoice{3},
        'invoiceUpdate'     => $invoice{4},
        'invoiceDelete'     => $invoice{5},

        'expenseViewAll'   => $expense{0},
        'expenseViewOwn'   => $expense{1},
        'expenseCreate'    => $expense{2},
        'expenseUpdate'    => $expense{3},
        'expenseDelete'    => $expense{4},

        'timesheetViewAll'   => $timesheet{0},
        'timesheetViewOwn'   => $timesheet{1},
        'timesheetCreate'    => $timesheet{2},
        'timesheetUpdate'    => $timesheet{3},
        'timesheetDelete'    => $timesheet{4},

        'filesView'      => $file{0},
        'filesCreate'    => $file{1},
        'filesUpdate'    => $file{2},
        'filesDelete'    => $file{3},

        'teamView'       => $team{0},
        'teamCreate'     => $team{1},
        'teamUpdate'     => $team{2},
        'teamDelete'     => $team{3},

        'messageViewAll'    => $message{0},
		'messageViewOwn'    => $message{1},
        'messageCreate'     => $message{2},
        'messageUpdate'     => $message{3},
        'messageDelete'     => $message{4},

        'calendarViewAll'   => $calendar{0},
        'calendarViewOwn'   => $calendar{1},
        'calendarCreate'    => $calendar{2},
        'calendarUpdate'    => $calendar{3},
        'calendarDelete'    => $calendar{4},

        'contactView'       => $contact{0},
        'contactCreate'     => $contact{1},
        'contactUpdate'     => $contact{2},
        'contactDelete'     => $contact{3},

        'trashViewAll'      => $trash{0},
        'trashViewOwn'      => $trash{1},

        'settingsViewAll'   => $settings{0},
        'settingsViewOwn'   => $settings{1}
    );

    return $permissions;
}

function createAuthKey($UID) {
    $CI =& get_instance();
    $CI->encrypt->set_cipher(MCRYPT_BLOWFISH);
    $authKey = $CI->encrypt->encode($UID);
    return $authKey;
}

function decryptAuthKey($authKey) {
    $CI =& get_instance();
    $CI->encrypt->set_cipher(MCRYPT_BLOWFISH);
    $decrypt = $CI->encrypt->decode($authKey);
    echo $decrypt;
}

function getAccountLevelSetting($setting=NULL) {
    global $accountLevelArray;
    $CI =& get_instance();
    return $accountLevelArray[$CI->session->userdata('accountLevel')][$setting];
}

function checkPermissionsForController($controller=NULL) {
    $CI =& get_instance();
    /*
     * Do we even have rights to be here?
     */

    $permArray = $CI->session->userdata('permissions');
    if ($controller == 'ProjectView' && $permArray['projectViewAll'] == 0 && $permArray['projectViewOwn'] == 0) {
        $redirect = 'dashboard/DashboardOwners';
    } elseif ($controller == 'ProjectUpdate' && $permArray['projectUpdate'] == 0) {
        $redirect = 'projects/ProjectView';
    } elseif ($controller == 'ClientView' && $permArray['clientView'] == 0) {
        $redirect = 'dashboard/DashboardOwners';
    } elseif ($controller == 'ClientUpdate' && $permArray['clientUpdate'] == 0) {
        $redirect = 'clients/ClientView';
    } elseif ($controller == 'FinanceView' && $permArray['invoiceViewAll'] == 0 && $permArray['invoiceViewOwn'] == 0 && $permArray['expenseViewAll'] == 0 && $permArray['expenseViewOwn'] == 0) {
        $redirect = 'dashboard/DashboardOwners';
    } elseif ($controller == 'InvoiceUpdate' && $permArray['invoiceUpdate'] == 0 && $permArray['invoiceCreateSend'] == 0 && $permArray['invoiceCreateSendToAccountOwner'] == 0) {
        $redirect = 'finances/FinanceView';
    } elseif ($controller == 'FileManager' && ($permArray['filesView'] == 0 || $CI->session->userdata('accountLevel') == 0)) {
        $redirect = 'dashboard/DashboardOwners';
    }    

    if (!empty($redirect)) {
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
            /*
             * This is an AJAX request, leave it alone and handle this some other way.
             */
        } else {
            header('Location: '.site_url($redirect));
        }
    }
}
?>